<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Shop\Model\ShopRecordsModel;
use App\Kuafu\Shop\Model\ShopStaffRecordModel;
use App\Kuafu\User\Model\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class RefreshShopStaffStatistics extends Command
{
    /**
     * shopIds 要重新统计的门店
     * updateHealthCardEndDate 是否修改了健康证时间
     * updateTime 商家更新时间 如果是0 则不更新
     * @var string
     */
    protected $signature = 'shop:refresh_shop_staff_statistics {--userIds=} {--updateHealthCardEndDate=0} {--updateTime=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新门店员工统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 更新状态
     * 更新统计
     */
    public function handle()
    {
        $userIds                  = (string)$this->option('userIds');
        $updateHealthCardEndDate = (int)$this->option('updateHealthCardEndDate');
        $updateTime              = (int)$this->option('updateTime');

        if (!strlen($userIds)) {
            return;
        } else {
            $userIds = explode(',', $userIds);
        }

        $shopIds = ShopStaffRecordModel::query()
            ->whereIn('userId', $userIds)
            ->pluck('shopId')
            ->toArray();

        $shopStaffList = [];

        // 变更了健康证时间  状态变更
        ShopStaffRecordModel::query()
            ->whereIn('shopId', $shopIds)
            ->with(['userRel.userIdCardRel'])
            ->chunk(50, function ($shopStaffs) use (&$shopStaffList, $updateHealthCardEndDate, $userIds) {
                // 数据初始化
                foreach ($shopStaffs as $staff) {
                    if (!isset($shopStaffList[$staff->shopId])) {
                        $shopStaffList[$staff->shopId] = [
                            'staffCount'        => 0,
                            'inShopStaffCount'  => 0,
                            'cardAbnormalCount' => 0,
                            'approvedCount'     => 0,
                            'rejectCount'       => 0,
                            'pendingCount'      => 0,
                            'aboutToExpireCount'=> 0,
                        ];
                    }
                }

                foreach ($shopStaffs as $staff) {
                    // 修改变更员工的状态
                    if (in_array($staff->userId, $userIds) ) {
                        // 状态变更
                        // 身份证状态
                        if (optional($staff->userRel)->userIdCardRel != null) {
                            $staff->idCardStatus = ShopStaffRecordModel::ID_CARD_STATUS_UPLOADED;
                        } else {
                            $staff->idCardStatus = ShopStaffRecordModel::ID_CARD_STATUS_LACK;
                        }

                        // 健康证状态
                        if (optional($staff->userRel)->healthCardEndDate == 0) {
                            $staff->healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_LACK;
                            $staff->auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_EXPIRED_OR_LACK;
                        } elseif (optional($staff->userRel)->healthCardEndDate > 0 && optional($staff->userRel)->healthCardEndDate <= time()) {
                            $staff->healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_EXPIRED;
                            $staff->auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_EXPIRED_OR_LACK;
                        } elseif (optional($staff->userRel)->healthCardEndDate > time() && optional($staff->userRel)->healthCardEndDate < Carbon::now()->addDays(30)->timestamp) {
                            $staff->healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_ABOUT_TO_EXPIRE;
                        } else {
                            $staff->healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_UPLOADED;
                        }

                        // 审核状态
                        if ($updateHealthCardEndDate && $staff->inShop == ShopStaffRecordModel::IN_SHOP_ON) {
                            $staff->auditStatus = ShopStaffRecordModel::AUDIT_STATUS_WAIT_AUDIT;
                        }

                        // 处理无需到店
                        if ($staff->inShop == ShopStaffRecordModel::IN_SHOP_OFF) {
                            $staff->auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_NOT_IN_SHOP;
                            //$staff->healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_NULL;
                            //$staff->idCardStatus     = ShopStaffRecordModel::ID_CARD_STATUS_DEFAULT;
                        }

                        // 处理已离职
                        if ($staff->positionStatus == ShopStaffRecordModel::POSITION_STATUS_OFF) {
                            $staff->auditStatus      = ShopStaffRecordModel::AUDIT_STATUS_LEAVE;
                            //$staff->healthCardStatus = ShopStaffRecordModel::HEALTH_CARD_STATUS_NULL;
                            //$staff->idCardStatus     = ShopStaffRecordModel::ID_CARD_STATUS_DEFAULT;
                        }

                        if ($staff->auditStatus != ShopStaffRecordModel::AUDIT_STATUS_REJECT) {
                            $staff->causeOfRejection = '';
                        }

                        // 更新状态
                        $staff->save();
                    }

                    // 数量统计
                    if ($staff->positionStatus == ShopStaffRecordModel::POSITION_STATUS_ON) {
                        // 在职员工
                        $shopStaffList[$staff->shopId]['staffCount'] += 1;

                        if ($staff->inShop == ShopStaffRecordModel::IN_SHOP_ON) {
                            // 到店员工
                            $shopStaffList[$staff->shopId]['inShopStaffCount'] += 1;

                            // 证件缺失员工
                            if (!optional($staff->userRel)->healthCardEndDate || !optional(optional($staff->userRel)->userIdCardRel)) {
                                $shopStaffList[$staff->shopId]['cardAbnormalCount'] += 1;
                            }

                            // 健康证过期
                            if ((int)optional($staff->userRel)->healthCardEndDate > 0 && (int)optional($staff->userRel)->healthCardEndDate < time()) {
                                $shopStaffList[$staff->shopId]['cardAbnormalCount'] += 1;
                            }

                            // 通过审核
                            if ($staff->auditStatus == ShopStaffRecordModel::AUDIT_STATUS_PASS) {
                                $shopStaffList[$staff->shopId]['approvedCount'] += 1;
                            }

                            // 驳回
                            if ($staff->auditStatus == ShopStaffRecordModel::AUDIT_STATUS_REJECT) {
                                $shopStaffList[$staff->shopId]['rejectCount'] += 1;
                            }

                            // 待审核
                            if ($staff->auditStatus == ShopStaffRecordModel::AUDIT_STATUS_WAIT_AUDIT) {
                                $shopStaffList[$staff->shopId]['pendingCount'] += 1;
                            }

                            // 健康证即将到期统计
                            if ($staff->healthCardStatus == ShopStaffRecordModel::HEALTH_CARD_STATUS_ABOUT_TO_EXPIRE) {
                                $shopStaffList[$staff->shopId]['aboutToExpireCount'] += 1;
                            }
                        }
                    }
                }
            });


        // ShopStaffRecordModel::query()
        //     ->where('userId', $userId)
        //     ->with(['userRel.userIdCardRel'])
        //     ->chunk(100, function ($shopStaffRecords) use (&$shopStaffList) {
        //         foreach ($shopStaffRecords as $shopStaffRecord) {
        //             if ($shopStaffRecord->positionStatus == ShopStaffRecordModel::POSITION_STATUS_ON) {
        //                 // 在职员工
        //                 $shopStaffList[$shopStaffRecord->shopId]['staffCount'] += 1;
        //
        //                 if ($shopStaffRecord->inShop == ShopStaffRecordModel::IN_SHOP_ON) {
        //                     // 到店员工
        //                     $shopStaffList[$shopStaffRecord->shopId]['inShopStaffCount'] += 1;
        //
        //                     // 证件缺失员工
        //                     if (!optional($shopStaffRecord->userRel)->healthCardEndDate || !optional(optional($shopStaffRecord->userRel)->userIdCardRel)) {
        //                         $shopStaffList[$shopStaffRecord->shopId]['cardAbnormalCount'] += 1;
        //                     }
        //
        //                     // 健康证过期
        //                     if ((int)optional($shopStaffRecord->userRel)->healthCardEndDate > 0 && (int)optional($shopStaffRecord->userRel)->healthCardEndDate < time()) {
        //                         $shopStaffList[$shopStaffRecord->shopId]['cardAbnormalCount'] += 1;
        //                     }
        //
        //                     // 通过审核
        //                     if ($shopStaffRecord->auditStatus == ShopStaffRecordModel::AUDIT_STATUS_PASS) {
        //                         $shopStaffList[$shopStaffRecord->shopId]['approvedCount'] += 1;
        //                     }
        //
        //                     // 驳回
        //                     if ($shopStaffRecord->auditStatus == ShopStaffRecordModel::AUDIT_STATUS_REJECT) {
        //                         $shopStaffList[$shopStaffRecord->shopId]['rejectCount'] += 1;
        //                     }
        //
        //                     // 待审核
        //                     if ($shopStaffRecord->auditStatus == ShopStaffRecordModel::AUDIT_STATUS_WAIT_AUDIT) {
        //                         $shopStaffList[$shopStaffRecord->shopId]['pendingCount'] += 1;
        //                     }
        //                 }
        //             }
        //         }
        //     });

        foreach ($shopStaffList as $shopId => $statistics) {
            Log::info('门店员工状态更新-shopId:' . $shopId . ' ' . json_encode($statistics, true));

            if ($updateTime != 0) {
                $statistics['lastManagerUpdateTime'] = $updateTime;
            }

            ShopRecordsModel::query()
                ->where('shopId', $shopId)
                ->update($statistics);
        }
    }
}
